<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { teacherApi } from '@/api/teacher'
import { courseApi } from '@/api/course'
import { studentApi } from '@/api/students'

const router = useRouter()
const authStore = useAuthStore()

// 表单数据
const formData = ref({
  className: '',
  classStuNum: 0 // 初始化为0
})

// 课程选择相关
const courses = ref([])
const selectedCourses = ref([])
const courseLoading = ref(false)

// 学生选择相关
const allStudents = ref([])
const selectedStudents = ref([])
const studentLoading = ref(false)
const studentSearchKeyword = ref('')

// 表单验证规则
const rules = {
  className: [
    { required: true, message: '请输入班级名称', trigger: 'blur' },
    { max: 20, message: '班级名称不能超过20个字符', trigger: 'blur' }
  ]
}

// 加载教师课程
const loadTeacherCourses = async () => {
  courseLoading.value = true
  try {
    const teacherId = authStore.userId
    const response = await teacherApi.getTeacherCourses(teacherId)
    courses.value = Array.isArray(response.data) ? response.data : 
                   Array.isArray(response) ? response : []
  } catch (error) {
    console.error('加载课程失败:', error)
    ElMessage.error('加载课程失败')
  } finally {
    courseLoading.value = false
  }
}

// 加载所有学生
const loadAllStudents = async () => {
  studentLoading.value = true
  try {
    const response = await studentApi.getAllStudents()
    const studentsData = Array.isArray(response.data) ? response.data : 
                        Array.isArray(response) ? response : []
    
    // 去重处理
    const studentsMap = {}
    studentsData.forEach(student => {
      if (student.id && !studentsMap[student.id]) {
        studentsMap[student.id] = {
          ...student,
          key: student.id,
          label: student.stuName || `学生${student.id}`
        }
      }
    })
    
    allStudents.value = Object.values(studentsMap)
  } catch (error) {
    console.error('加载学生列表失败:', error)
    ElMessage.error('加载学生列表失败')
  } finally {
    studentLoading.value = false
  }
}

// 搜索学生
const searchStudents = async () => {
  if (!studentSearchKeyword.value.trim()) {
    await loadAllStudents()
    return
  }

  studentLoading.value = true
  try {
    const response = await studentApi.searchStudents(studentSearchKeyword.value)
    const searchResults = Array.isArray(response.data) ? response.data : 
                         Array.isArray(response) ? response : []
    
    // 去重处理
    const studentsMap = {}
    searchResults.forEach(student => {
      if (student.id && !studentsMap[student.id]) {
        studentsMap[student.id] = {
          ...student,
          key: student.id,
          label: student.stuName || `学生${student.id}`
        }
      }
    })
    
    allStudents.value = Object.values(studentsMap)
  } catch (error) {
    console.error('搜索学生失败:', error)
    ElMessage.error('搜索学生失败')
  } finally {
    studentLoading.value = false
  }
}

// 提交表单（核心修改部分）
// 提交表单（核心修改部分）
// 提交表单（核心修改部分）
// 提交表单（核心修改部分）
const submitForm = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在创建班级...'
  })
  
  try {
    // 1. 创建班级基本信息
    const payload = {
      className: formData.value.className.trim(),
      classStuNum: 0, // 默认设为0
      teacherId: authStore.userId,
      courseIds: selectedCourses.value // 添加课程ID列表
    }
    
    console.log('创建班级请求数据:', payload)
    
    // 使用正确的API方法名
    const classResponse = await teacherApi.createClass(payload)
    
    // 检查响应结构
    console.log('创建班级响应:', classResponse)
    
    const classId = classResponse.data?.id || classResponse.id
    if (!classId) {
      throw new Error('创建班级失败，未获取到班级ID')
    }
    
    // 2. 添加学生到班级（可选）
    if (selectedStudents.value.length > 0) {
      console.log('添加学生:', selectedStudents.value)
      await studentApi.batchAddStudentsToClass(classId, selectedStudents.value)
        .catch(err => console.warn('添加学生失败:', err))
    }
    
    ElMessage.success('班级创建成功')
    router.push('/teacher-class/list')
  } catch (error) {
    console.error('创建班级失败:', error)
    const serverMessage = error.response?.data?.message || 
                         error.response?.data?.error || 
                         error.message
    ElMessage.error(`创建班级失败: ${serverMessage}`)
  } finally {
    loadingInstance.close()
  }
}

// 初始化加载
onMounted(() => {
  loadTeacherCourses()
  loadAllStudents()
})
</script>

<template>
  <div class="add-class-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>创建新班级</h2>
        </div>
      </template>
      
      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef"
        label-width="120px"
        class="class-form"
      >
        <!-- 班级基本信息 -->
        <el-form-item label="班级名称" prop="className">
          <el-input 
            v-model="formData.className" 
            placeholder="请输入班级名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        
        <!-- 班级课程选择 -->
        <el-form-item label="班级课程">
          <el-select
            v-model="selectedCourses"
            multiple
            filterable
            placeholder="请选择课程"
            style="width: 100%"
            :loading="courseLoading"
          >
            <el-option
              v-for="course in courses"
              :key="course.id"
              :label="course.courseName || `课程${course.id}`"
              :value="course.id"
            >
              <span>{{ course.courseName || `课程${course.id}` }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                {{ course.id }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 班级学生选择 -->
        <el-form-item label="班级学生">
          <div class="student-selector">
            <div class="search-bar">
              <el-input
                v-model="studentSearchKeyword"
                placeholder="搜索学生"
                clearable
                @clear="loadAllStudents"
                @keyup.enter="searchStudents"
              >
                <template #append>
                  <el-button @click="searchStudents">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
            
            <el-transfer
              v-model="selectedStudents"
              :data="allStudents"
              :titles="['所有学生', '已选学生']"
              :props="{
                key: 'id',
                label: 'stuName'
              }"
              :loading="studentLoading"
              filterable
              filter-placeholder="输入学生姓名搜索"
              style="margin-top: 15px"
            />
          </div>
        </el-form-item>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">创建班级</el-button>
          <el-button @click="router.push('/teacher-class/list')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
/* 保持原有样式不变 */
.add-class-container {
  padding: 20px;
}

.box-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.class-form {
  max-width: 800px;
  margin: 0 auto;
}

.student-selector {
  width: 100%;
}

.search-bar {
  margin-bottom: 15px;
}

.el-transfer {
  display: flex;
  justify-content: center;
}

.el-select {
  width: 100%;
}

.el-input {
  width: 100%;
}
</style>